using AutoMapper;
using MediatR;
using S.M.SmartMedical.API.Write.Application.Command;
using S.M.SmartMedical.Domain.DTOs;
using S.M.SmartMedical.Domain.Entities;
using S.M.SmartMedical.Domain.Enums;
using S.M.SmartMedical.ErrorCode;
using S.M.SmartMedical.Infrastructure;
using S.M.SmartMedical.Infrastructure.BaseRepository;

namespace S.M.SmartMedical.API.Write.Application.Handler
{
    /// <summary>
    /// 创建轮播图命令处理器
    /// </summary>
    public class CreateCarouselHandler : IRequestHandler<CreateCarouselCommand, APIResult<CarouselDto>>
    {
        private readonly IRepository<Carousel> _carouselRepository;
        private readonly IMapper _mapper;
        private readonly ILogger<CreateCarouselHandler> _logger;
        private readonly MyDbContext _context;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="carouselRepository">轮播图仓储</param>
        /// <param name="mapper">对象映射器</param>
        /// <param name="logger">日志记录器</param>
        /// <param name="context">数据库上下文</param>
        public CreateCarouselHandler(
            IRepository<Carousel> carouselRepository,
            IMapper mapper,
            ILogger<CreateCarouselHandler> logger,
            MyDbContext context)
        {
            _carouselRepository = carouselRepository;
            _mapper = mapper;
            _logger = logger;
            _context = context;
        }

        /// <summary>
        /// 处理创建轮播图命令
        /// </summary>
        /// <param name="request">创建轮播图命令</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>创建结果</returns>
        public async Task<APIResult<CarouselDto>> Handle(CreateCarouselCommand request, CancellationToken cancellationToken)
        {
            try
            {
                _logger.LogInformation("开始处理创建轮播图，标题：{Title}", request.Carousel.Title);

                // 将DTO映射为实体
                var carousel = _mapper.Map<Carousel>(request.Carousel);

                // 设置实体的必要属性
                carousel.UploadTime = DateTime.Now;
                carousel.Uploader = "admin"; // 实际应用中应该从登录用户获取
                carousel.CreateTime = DateTime.Now;
                carousel.CreateUserName = "admin";
                carousel.IsDeleted = false;
                carousel.SortOrder = request.Carousel.Sort;

                // 添加到仓储
                var result = await _carouselRepository.AddAsync(carousel);

                // 保存到数据库
                var saveResult = await _context.SaveChangesAsync(cancellationToken);

                if (saveResult > 0)
                {
                    _logger.LogInformation("轮播图创建成功，标题：{Title}，ID：{Id}", carousel.Title, carousel.Id);

                    // 映射返回数据
                    var carouselDto = _mapper.Map<CarouselDto>(carousel);
                    return new APIResult<CarouselDto>
                    {
                        Code = APIEnum.OK,
                        Message = "轮播图创建成功",
                        Data = carouselDto
                    };
                }
                else
                {
                    _logger.LogError("轮播图创建失败，数据库保存失败，标题：{Title}", request.Carousel.Title);
                    return new APIResult<CarouselDto>
                    {
                        Code = APIEnum.Fail,
                        Message = "轮播图创建失败，请稍后重试",
                        Data = null!
                    };
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "创建轮播图过程中发生异常，标题：{Title}", request.Carousel.Title);
                return new APIResult<CarouselDto>
                {
                    Code = APIEnum.Fail,
                    Message = "创建轮播图失败，系统异常",
                    Data = null!
                };
            }
        }
    }
}